﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Commond.AdminSetting;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Common.Menus;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Domain.DTO;
using SmartCity.BasicData.Repo;
using System.Linq.Expressions;

namespace SmartCity.BasicData.Api.Application.Handler.AdminSetting
{
    public class AccountListSearchHandler : IRequestHandler<AccountLIstSearchCommand, ApiResult<IList<AccountDepartmentDTO>>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<DepartmentsModel> departMentRepo;
        private readonly IBaseRepository<RoleModel> roleRep;
        private readonly IMapper mapper;
        private readonly ILogger<AccountListSearchHandler> logger;

        /// <summary>
        /// 通过构造函数注入账号仓储,Department仓储,角色仓储  ,automap组件,NLog日志组件
        /// </summary>
        public AccountListSearchHandler(IBaseRepository<AccountModel> accountRepo, IBaseRepository<DepartmentsModel> departMentRepo, IBaseRepository<RoleModel> roleRep,IMapper mapper,ILogger<AccountListSearchHandler> logger)
        {
            this.accountRepo = accountRepo;
            this.departMentRepo = departMentRepo;
            this.roleRep = roleRep;
            this.mapper = mapper;
            this.logger = logger;
        }
        public Task<ApiResult<IList<AccountDepartmentDTO>>> Handle(AccountLIstSearchCommand request, CancellationToken cancellationToken)
        {
            ApiResult<IList<AccountDepartmentDTO>> result = new ApiResult<IList<AccountDepartmentDTO>>();

            try
            {
                var accounts = new List<AccountModel>();//所有的用户 变量

                if (!string.IsNullOrEmpty(request.AccountNickname))//判断姓名是否为空
                {
                    //查询条件里要过滤用户
                    accounts = accountRepo.GetAsync(acc => acc.AccountNickname.Contains(request.AccountNickname)&&!acc.IsDeleted).Result;
                }
                else
                {
                    //姓名为空,条件里没有过滤用户
                    accounts = accountRepo.GetAsync(acc=>!acc.IsDeleted).Result;
                }

                //var acccounts_quary = accountRepo.QueryAllAsync().Result;//select * from  acccounts
                //if (!string.IsNullOrEmpty(request.AccountNickname))
                //{
                //    // where nickname like'%nickname%'
                //    acccounts_quary = acccounts_quary.Where(x => x.AccountNickname.Contains(request.AccountNickname) && !x.IsDeleted);
                //}


                var roles = roleRep.GetAllAsync().Result;//所有部门
                var departments = new List<DepartmentsModel>();//所有的部门

                if (!string.IsNullOrEmpty(request.DepartName))
                {
                    departments = departMentRepo.GetAsync(depart => depart.DepartmentName.Contains(request.DepartName)).Result;
                }
                else
                {
                    departments = departMentRepo.GetAllAsync().Result;
                }

                //连接查询  join
                var linq = from acc in accounts //select acc.id,acc.AccountName from accounts as acc
                           join depart in departments on acc.DepartmentId equals depart.Id //select depart.id from departments as depart
                           join role in roles on acc.RoleId equals role.Id
                           select new AccountDepartmentDTO
                           {
                               Id=acc.Id,
                               AccountName = acc.AccountName,
                               AccountNickname = acc.AccountNickname,
                               AccountPhone = acc.AccountPhone,
                               AccountCard = acc.AccountCard,
                               RoleName = role.RoleName,
                               DepartmentName = depart.DepartmentName,
                               RoleId = role.Id,
                               DepartmentId=acc.DepartmentId
                           };
                result.Data = linq.ToList();
                result.Code = EnumResultCode.Success;
                result.Msg = "查询成功";
            }
            catch (Exception e)
            {
                
                result.Code = EnumResultCode.Fail;
                result.Msg = "查询失败";
                logger.LogError("查询管理员设置列表发生异常:"+e.Message);
               
            }
            return Task.FromResult(result);
        }
    }
}
